﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using System.Xml.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace Common
{
    /// <summary>
    /// 序列化相关帮助类
    /// </summary>
    public static class SerializeHelper
    {
        /// <summary>
        /// 序列化对象到字符串
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string SerializeToString(object obj)
        {
            string result = string.Empty;
            BinaryFormatter binaryFormat = new BinaryFormatter();
            using (MemoryStream ms = new MemoryStream())
            {
                binaryFormat.Serialize(ms, obj);
                byte[] bs = ms.ToArray();
                result = Convert.ToBase64String(bs);
            }
            return result;
        }
        /// <summary>
        /// 反序列化字符串到对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="str"></param>
        /// <returns></returns>
        public static T DeserializeByString<T>(string str)
        {
            if (str == string.Empty)
                return default(T);
            T t = default(T);
            BinaryFormatter formatter = new BinaryFormatter();
            byte[] bs = Convert.FromBase64String(str);
            using (MemoryStream ms = new MemoryStream(bs))
            {
                t = (T)formatter.Deserialize(ms);
            }
            return t;
        }

        /// <summary>
        /// 序列化对象到字节数组
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static byte[] SerializeToBytes(object obj)
        {
            byte[] bs;
            string result = string.Empty;
            BinaryFormatter binaryFormat = new BinaryFormatter();
            using (MemoryStream ms = new MemoryStream())
            {
                binaryFormat.Serialize(ms, obj);
                bs = ms.ToArray();
            }
            return bs;
        }
        /// <summary>
        /// 反序列化字节数组到对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="bs"></param>
        /// <returns></returns>
        public static T DeserializeByBytes<T>(byte[] bs)
        {
            if (bs == null)
                return default(T);
            T t = default(T);
            BinaryFormatter formatter = new BinaryFormatter();
            using (MemoryStream ms = new MemoryStream(bs))
            {
                t = (T)formatter.Deserialize(ms);
            }
            return t;
        }

        /// <summary>
        /// 序列化对象到文件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="filePath"></param>
        /// <param name="t"></param>
        public static void FileSerialize(string filePath, object obj)
        {
            lock (_Root)
            {
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }
                using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    formatter.Serialize(fs, obj);
                    fs.Flush();
                }
            }
        }
        /// <summary>
        /// 反序列化文件到对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static T FileDeserialize<T>(string filePath)
        {
            lock (_Root)
            {
                if (!File.Exists(filePath))
                    return default(T);
                using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None))
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    return (T)formatter.Deserialize(fs);
                }
            }
        }

        /// <summary>
        /// 序列化对象到Xml文件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="filePath"></param>
        /// <param name="t"></param>
        public static void XmlSerialize(string filePath, object obj)
        {
            lock (_Root)
            {
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }
                using (StreamWriter writer = new StreamWriter(filePath, false, Encoding.UTF8))
                {
                    XmlSerializer xs = new XmlSerializer(obj.GetType());
                    xs.Serialize(writer, obj);
                    writer.Flush();
                }
            }
        }
        /// <summary>
        /// 反序列化Xml文件到对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static T XmlDeserialize<T>(string filePath)
        {
            T t = default(T);
            lock (_Root)
            {
                if (!File.Exists(filePath))
                    return t;
                using (StreamReader reader = new StreamReader(filePath, Encoding.UTF8, false))
                {
                    XmlSerializer xs = new XmlSerializer(typeof(T));
                    Object obj = xs.Deserialize(reader);
                    if (obj is T)
                        t = (T)obj;
                }
            }
            return t;
        }
    }
}
